<template>
  <div id="container" ></div>
  <el-drawer v-model="drawer"  :with-header="false">
    <el-descriptions title="详细信息" direction="vertical" border >
    <el-descriptions-item label="name"><el-tag>{{currentDrawer.name}}</el-tag></el-descriptions-item>
    <el-descriptions-item label="input_shape">{{currentDrawer.input_shape}}</el-descriptions-item>
    <el-descriptions-item label="out_shape">{{currentDrawer.out_shape}}</el-descriptions-item>
  </el-descriptions>
    <div>doc:</div>
    <el-input
    v-model="currentDrawer.doc"
    :rows="2"
    :autosize="{ minRows: 2, maxRows: 20 }"
    type="textarea"
    disabled
  />
  </el-drawer>
</template>

<script setup>
import G6 from '@antv/g6';
import { onMounted } from 'vue'
import { ref } from 'vue'
import {useRoute} from 'vue-router'
import { HandleLayerLog } from '@/api.js'
let mockData={};
const route =useRoute()
HandleLayerLog(route.query.id).then(res=>{
  console.log(res);

  mockData=res.layers;
  
  console.log(mockData);
  const props = {
    data: mockData,
    config: {
      padding: [20, 50],
      defaultLevel: 3,
      defaultZoom: 0.8,
      modes: { default: ['zoom-canvas', 'drag-canvas'] },
    },
  };

  const container = document.getElementById('container');
  console.log(container);
  const width = container.scrollWidth;
  const height = container.scrollHeight || 500;

  // 默认配置
  const defaultConfig = {
    width,
    height,
    modes: {
      default: ['zoom-canvas', 'drag-canvas'],
    },
    fitView: true,
    animate: true,
    defaultNode: {
      type: 'flow-rect',
    },
    defaultEdge: {
      type: 'cubic-horizontal',
      style: {
        stroke: '#CED4D9',
      },
    },
    layout: {
      type: 'indented',
      direction: 'LR',
      dropCap: false,
      indent: 300,
      getHeight: () => {
        return 60;
      },
    },
  };

  // 自定义节点、边
  const registerFn = () => {
    /**
     * 自定义节点
     */
    G6.registerNode(

      'flow-rect',

      {
        shapeType: 'flow-rect',
        draw(cfg, group) {
          const {
            name = '',
            channels,
            input_shape,
            collapsed,
            out_shape

          } = cfg;
          const grey = '#CED4D9';
          // 逻辑不应该在这里判断
          const rectConfig = {
            width: 202,
            height: 60,
            lineWidth: 1,
            fontSize: 12,
            fill: '#fff',
            radius: 4,
            stroke: grey,
            opacity: 1,
          };
          const nodeOrigin = {
            x: -rectConfig.width / 2,
            y: -rectConfig.height / 2,
          };
          const rect = group.addShape('rect', {
            attrs: {
              x: nodeOrigin.x,
              y: nodeOrigin.y,
              ...rectConfig,
            },
          });
          const rectBBox = rect.getBBox();


          const textConfig = {
            textAlign: 'left',
            textBaseline: 'bottom',
          };


          const inputShape = group.addShape('text', {
            attrs: {
              ...textConfig,
              x: rectBBox.maxX - 50,
              y: 20 + nodeOrigin.y,
              text: input_shape,
              fontSize: 10,
              fill: '#000',
              opacity: 0.85,
            },
          });


          // const symbol = variableUp ? 'triangle' : 'triangle-down';
          group.addShape('marker', {
            attrs: {
              ...textConfig,
              x: rectBBox.maxX - 60,
              y: 14 + nodeOrigin.y,
              symbol: 'triangle',
              r: 4,
              fill: '#5B8FF9',
            },
          });

          group.addShape('marker', {
            attrs: {
              ...textConfig,
              x: rectBBox.maxX - 60,
              y: 45 + nodeOrigin.y,
              symbol: 'triangle-down',
              r: 4,
              fill: '#F46649',
            },
          });

          group.addShape('text', {
            attrs: {
              ...textConfig,
              x: rectBBox.maxX - 50,
              y: 50 + nodeOrigin.y,
              text: out_shape,
              fontSize: 10,
              fill: '#000',
              opacity: 0.85,
            },
          });
          // channel title
          group.addShape('text', {
            attrs: {
              ...textConfig,
              x: 12 + nodeOrigin.x,
              y: 20 + nodeOrigin.y,
              text: name.length > 28 ? name.substr(0, 28) + '...' : name,
              fontSize: 12,
              opacity: 0.85,
              fill: '#000',
              cursor: 'pointer',
            },
            name: 'name-shape',
          });

          
          group.addShape('text', {
            attrs: {
              ...textConfig,
              x: 12 + nodeOrigin.x,
              y: rectBBox.maxY - 8,
              text: channels,
              fontSize: 16,
              fill: '#000',
              opacity: 0.85,
            },
          });


          // collapse rect
          if (cfg.children && cfg.children.length) {
            group.addShape('rect', {
              attrs: {
                x: rectConfig.width / 2 - 8,
                y: -8,
                width: 16,
                height: 16,
                stroke: 'rgba(0, 0, 0, 0.25)',
                cursor: 'pointer',
                fill: '#fff',
              },
              name: 'collapse-back',
              modelId: cfg.id,
            });

            // collpase text
            group.addShape('text', {
              attrs: {
                x: rectConfig.width / 2,
                y: -1,
                textAlign: 'center',
                textBaseline: 'middle',
                text: collapsed ? '+' : '-',
                fontSize: 16,
                cursor: 'pointer',
                fill: 'rgba(0, 0, 0, 0.25)',
              },
              name: 'collapse-text',
              modelId: cfg.id,
            });
          }

          this.drawLinkPoints(cfg, group);
          return rect;
        },
        update(cfg, item) {
          const group = item.getContainer();
          this.updateLinkPoints(cfg, group);
        },
        setState(name, value, item) {
          if (name === 'collapse') {
            const group = item.getContainer();
            const collapseText = group.find((e) => e.get('name') === 'collapse-text');
            if (collapseText) {
              if (!value) {
                collapseText.attr({
                  text: '-',
                });
              } else {
                collapseText.attr({
                  text: '+',
                });
              }
            }
          }
        },
        getAnchorPoints() {
          return [
            [0, 0.5],
            [1, 0.5],
          ];
        },
      },
      'rect',
    );

    G6.registerEdge(
      'flow-cubic',
      {
        getControlPoints(cfg) {
          let controlPoints = cfg.controlPoints; // 指定controlPoints
          if (!controlPoints || !controlPoints.length) {
            const { startPoint, endPoint, sourceNode, targetNode } = cfg;
            const { x: startX, y: startY, coefficientX, coefficientY } = sourceNode
              ? sourceNode.getModel()
              : startPoint;
            const { x: endX, y: endY } = targetNode ? targetNode.getModel() : endPoint;
            let curveStart = (endX - startX) * coefficientX;
            let curveEnd = (endY - startY) * coefficientY;
            curveStart = curveStart > 40 ? 40 : curveStart;
            curveEnd = curveEnd < -30 ? curveEnd : -30;
            controlPoints = [
              { x: startPoint.x + curveStart, y: startPoint.y },
              { x: endPoint.x + curveEnd, y: endPoint.y },
            ];
          }
          return controlPoints;
        },
        getPath(points) {
          const path = [];
          path.push(['M', points[0].x, points[0].y]);
          path.push([
            'C',
            points[1].x,
            points[1].y,
            points[2].x,
            points[2].y,
            points[3].x,
            points[3].y,
          ]);
          return path;
        },
      },
      'single-line',
    );
  };

  registerFn();

  const { data } = props;
  let graph = null;

  const initGraph = (data) => {
    if (!data) {
      return;
    }
    const { onInit, config } = props;
    const tooltip = new G6.Tooltip({
      // offsetX and offsetY include the padding of the parent container
      offsetX: 20,
      offsetY: 30,
      // the types of items that allow the tooltip show up
      // 允许出现 tooltip 的 item 类型
      itemTypes: ['node'],
      // custom the tooltip's content
      // 自定义 tooltip 内容
      getContent: (e) => {
        const outDiv = document.createElement('div');
        //outDiv.style.padding = '0px 0px 20px 0px';
        const nodeName = e.item.getModel().name;
        // console.log(e.item.getModel());
        let formatedNodeName = '';
        for (let i = 0; i < nodeName.length; i++) {
          formatedNodeName = `${formatedNodeName}${nodeName[i]}`;
          if (i !== 0 && i % 20 === 0) formatedNodeName = `${formatedNodeName}<br/>`;
        }
        outDiv.innerHTML = `${formatedNodeName}`;
        return outDiv;
      },
      shouldBegin: (e) => {
        if (e.target.get('name') === 'name-shape') return true;
        return false;
      },
    });
    graph = new G6.TreeGraph({

      container: 'container',
      ...defaultConfig,
      ...config,
      plugins: [tooltip],
    });
    if (typeof onInit === 'function') {
      onInit(graph);
    }
    graph.data(data);
    graph.render();
    graph.zoom(config.defaultZoom || 1);

    const handleCollapse = (e) => {
      const target = e.target;
      const id = target.get('modelId');
      const item = graph.findById(id);
      const nodeModel = item.getModel();
      nodeModel.collapsed = !nodeModel.collapsed;
      graph.layout();
      graph.setItemState(item, 'collapse', nodeModel.collapsed);
    };
    graph.on('collapse-text:click', (e) => {
      handleCollapse(e);
    });
    graph.on('collapse-back:click', (e) => {
      handleCollapse(e);
    });
    graph.on('node:dblclick', (e) => {
      currentDrawer.value=e.item._cfg.model
      drawer.value = true
    })
  };

  initGraph(data);

  if (typeof window !== 'undefined')
    window.onresize = () => {
      if (!graph || graph.get('destroyed')) return;
      if (!container || !container.scrollWidth || !container.scrollHeight) return;
      graph.changeSize(container.scrollWidth, container.scrollHeight);
    };
})


const currentDrawer=ref({});
const drawer = ref(false)

const colors = {
  B: '#5B8FF9',
  R: '#F46649',
  Y: '#EEBC20',
  G: '#5BD8A6',
  DI: '#A7A7A7',
};

onMounted(() => {
  //  组件props
  
})
</script>

<style>
#relationChart {
  height: 500px;
  width: 500px;
}
</style>